<template>
  <div>
    <div class="container">
      <div class="handle-box" style="display: flex">
        <!--        <el-select v-model="query.address" placeholder="地址" class="handle-select mr10">-->
        <!--          <el-option key="1" label="广东省" value="广东省"></el-option>-->
        <!--          <el-option key="2" label="湖南省" value="湖南省"></el-option>-->
        <!--        </el-select>-->

        <el-input v-model="student.id" class="handle-input mr10">
          <template #prepend>编号</template>
        </el-input>
        <el-input v-model="student.name" class="handle-input mr10">
          <template #prepend>姓名</template>
        </el-input>
        <el-input v-model="student.classes.name" class="handle-input mr10">
          <template #prepend>班级名称</template>
        </el-input>
        <el-input v-model="student.sex" class="handle-input mr10">
          <template #prepend>性别</template>
        </el-input>
        <el-date-picker
          style="width: 14%; margin-right: 10px"
          v-model="student.birthday"
          type="date"
          placeholder="畜生日期"
          value-format="YYYY-MM-DD"
        >
        </el-date-picker>
        <el-input v-model="student.college" class="handle-input mr10">
          <template #prepend>学院</template>
        </el-input>
        <el-button type="primary" :icon="Search" @click="handleSearch"
          >搜索</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          prop="id"
          label="学生编号"
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="学生姓名"
          width="140"
          align="center"
        ></el-table-column>
        <!--        <el-table-column label="头像(查看大图)" align="center">-->
        <!--          <template #default="scope">-->
        <!--            <el-image-->
        <!--                class="table-td-thumb"-->
        <!--                :src="scope.row.thumb"-->
        <!--                :z-index="10"-->
        <!--                :preview-src-list="[scope.row.thumb]"-->
        <!--                preview-teleported-->
        <!--            >-->
        <!--            </el-image>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="状态" align="center">-->
        <!--          <template #default="scope">-->
        <!--            <el-tag-->
        <!--                :type="scope.row.state === '成功' ? 'success' : scope.row.state === '失败' ? 'danger' : ''"-->
        <!--            >-->
        <!--              {{ scope.row.state }}-->
        <!--            </el-tag>-->
        <!--          </template>-->
        <!--        </el-table-column>-->

        <el-table-column
          prop="classes.id"
          label="班级编号"
          width="110"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="classes.name"
          label="班级名称"
          width="110"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="sex"
          label="性别"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="birthday"
          label="生日"
          width="110"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="college"
          label="学院"
          width="120"
          align="center"
        ></el-table-column>
        <!--        <el-table-column prop="date" label="注册时间"></el-table-column>-->
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button
              text
              :icon="Edit"
              @click="handleEdit(scope.$index, scope.row)"
              v-permiss="15"
            >
              编辑
            </el-button>
            <el-button
              text
              :icon="Delete"
              class="red"
              @click="handleDelete(scope.row.id, scope.$index)"
              v-permiss="16"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
        <el-button type="danger" :icon="Delete" @click="deleteData"
          >批量删除</el-button
        >
        <el-button type="primary" :icon="UploadFilled" @click="importData"
          >导入</el-button
        >
        <el-button type="primary" :icon="Download" @click="exportData"
          >导出</el-button
        >
        <el-button type="primary" :icon="Plus" @click="saveStudent1"
          >新增</el-button
        >
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog v-if="saveStudent1" v-model="editVisible" width="30%">
      <el-form label-width="70px">
        <el-form-item label="编号">
          <el-input v-model="formdata.id"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="formdata.name"></el-input>
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="formdata.classId" placeholder="请选择班级">
            <el-option
              v-for="item in classes"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="formdata.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker
            v-model="formdata.birthday"
            type="date"
            value-format="YYYY-MM-DD"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="学院">
          <el-input v-model="formdata.college"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="saveStudent1 = false">取 消</el-button>
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑弹出框 -->
    <el-dialog :title="title" v-model="editVisible" width="30%">
      <el-form label-width="70px">
        <el-form-item label="编号">
          <el-input v-model="formdata.id"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="formdata.name"></el-input>
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="formdata.classId" placeholder="请选择班级">
            <el-option
              v-for="item in classes"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="formdata.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker
            v-model="formdata.birthday"
            type="date"
            value-format="YYYY-MM-DD"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="学院">
          <el-input v-model="formdata.college"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Delete,
  Edit,
  Search,
  Plus,
  UploadFilled,
  Download,
} from "@element-plus/icons-vue";
import { upStudent, importExcel, deleteStudents } from "../api/student";

// import {handleDelete} from '../api/student';

// interface TableItem {
//   id: number;
//   name: string;
//   money: string;
//   state: string;
//   date: string;
//   address: string;
// }

const query = reactive({
  pageIndex: 1,
  pageSize: 3,
});
const tableData = ref([]);
const pageTotal = ref(0);

let student = reactive({
  id: "",
  name: "",
  classId: "",
  sex: "",
  birthday: "",
  college: "",
  classes: { id: "", name: "" },
  fileInput: null,
});
// 获取表格数据
const getData = () => {
  getStudentPager(query, student).then((res) => {
    tableData.value = res.data.list;
    pageTotal.value = res.data.pageTotal || 50;
    query.pageIndex = res.data.pageNum;
    query.pageSize = res.data.pageSize;
  });
};

getData();

// 查询操作
const handleSearch = () => {
  getData();
};
// 分页导航
const handlePageChange = (val: number) => {
  query.pageIndex = val;
  getData(query);
};

// 删除操作
const handleDelete = (id: string, index: number) => {
  // 二次确认删除
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  }).then(() => {
    deleteStudent(id)
      .then((res) => {
        if (res.data === 1) {
          ElMessage.success("删除成功！");
          //移除表格中的当前行，不用重新刷新数据
          tableData.value.splice(index, 1);
        } else {
          ElMessage.error("删除失败！");
        }
      })
      .catch((error) => ElMessage.error(error));
  });
};

// 表格编辑时弹窗和保存
const editVisible = ref(false);
const title = ref("");
let formdata: any = reactive({});
let classes: any = ref([]);
const saveStudent1 = ref(false);

getAllClasses()
  .then((res) => {
    classes.value = res.data;
  })
  .catch((err) => alert(err));

//保存学生,完成新增与编辑功能
function saveStudent() {
  if (classes.value.length <= 0) {
    getAllClasses()
      .then((res) => {
        classes.value = res.data;
        title.value = "新增学生";
        Object.assign("null");
        editVisible.value = true;
        console.log(classes);
      })
      .catch((err) => alert(err));
  } else {
    title.value = "新增学生";
    editVisible.value = true;
  }
}

const handleEdit = (index: number, row: any) => {
  title.value = "编辑学生";
  Object.assign(formdata, row);
  editVisible.value = true;
};

//添加/修改
const saveEdit = () => {
  if (title.value === "新增学生") {
    formdata.close();
    //添加学生
    addStudent(formdata).then((res) => {
      if (res.data === 1) {
        ElMessage({
          message: "新添加学生成功！",
          type: "success",
        });
        getData();
        editVisible.value = false;
        formdata.value = {};
      } else {
        ElMessage.error("新添加学生失败！");
      }
    });
  }
  if (title.value === "编辑学生") {
    //修改学生信息
    upStudent(formdata)
      .then((res) => {
        if (res.data === 1) {
          ElMessage.success("修改成功！");
          getData();
          editVisible.value = false;
        } else {
          ElMessage.error("修改失败！");
        }
      })
      .catch((error) => ElMessage.error(error));
  }
};

const multipleSelection = ref([]);
//批量删除
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
  console.log(val);
};
const deleteData = () => {
  if (multipleSelection.value.length <= 0) {
    ElMessage.error("请至少选择一项进行删除！");
    return;
  } else {
    //二次确认删除
    ElMessageBox.confirm("确定要删除吗？", "提示", {
      type: "warning",
    }).then(() => {
      const ids: string[] = [];
      multipleSelection.value.forEach((item: any) => {
        ids.push(item.id);
      });
      deleteStudents(ids)
        .then((res) => {
          if (res.data >= 1) {
            ElMessage.success(`成功删除${res.data}!`);
            getData();
          } else {
            ElMessage.error("删除失败！");
          }
        })
        .catch((error) => ElMessage.error(error));
    });
  }
};

let fileInput: any = null;
//导入
const importData = () => {
  if (!fileInput) {
    //创建一个input在页面上
    fileInput = document.createElement("input");
    fileInput.setAttribute("type", "file");
    fileInput.setAttribute("hidden", "true");
    fileInput.setAttribute("name", "file");
    document.body.appendChild(fileInput);

    //触发文件上传
    fileInput.addEventListener(
      "change",
      function (e: any) {
        //获取当前要上传的文件
        const file = e.target.files[0];
        //创建要上传的表单数据
        const formDate = new FormData();
        formDate.append("file", file);

        importExcel(formDate)
          .then((res) => {
            ElMessage.success("上传数据成功，添加了" + res.data + "行数据！");
            getData();
          })
          .catch((err) => ElMessage.error(err));
      },
      true
    );
  }
  fileInput.value;
  fileInput.click();
};
//导出
const exportData = () => {
  const stu = student;
  let url = "http://127.0.0.1:1234/Hi/exportExcel";
  url += `?id=${stu.id}&name=${stu.name}&classId=${stu.classId}&sex=${stu.sex}&birthday=${stu.birthday}&college=${stu.college}&classname=${stu.classes.name}`;
  location.href = url;
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 14%;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #f56c6c;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
